<template>
    <div class="vue-body" >
        <!-- 搜索条件, 按钮 放在一行 -->
        <div class="btn-header">
            <!-- 搜索条件 -->
            <div>
                <el-input style="width: 200px; margin-right: 5px;" placeholder="请输入用户名" suffix-icon="el-icon-search"
                          v-model="params.name"></el-input>
                <el-input style="width: 200px; margin-right: 5px;" placeholder="请输入昵称" suffix-icon="el-icon-position"
                          v-model="params.nickname"></el-input>
                <el-input style="width: 200px; margin-right: 5px;" placeholder="请输入角色" suffix-icon="el-icon-message"
                          v-model="params.name"></el-input>
                <el-button type="primary" @click="load">搜索</el-button>
            </div>
            
            <!-- 操作按钮 -->
            <div class="btn-inner-div">
                <el-button type="primary" @click="add">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
                <el-button type="danger">批量删除 <i class="el-icon-remove-outline"></i></el-button>
                <el-button type="primary">导入 <i class="el-icon-bottom"></i></el-button>
                <el-button type="primary">导出 <i class="el-icon-top"></i></el-button>
            </div>
        </div>
        
        <!-- 列表查询 -->
        <el-table :data="tableData" border stripe :header-cell-class-name="headerBg" v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" sortable align="center"></el-table-column>
            <el-table-column prop="name" label="用户名" width="140" align="center"></el-table-column>
            <el-table-column prop="nickname" label="用户昵称" width="200" align="center"></el-table-column>
            <el-table-column prop="salt" label="盐值" width="200" align="center"></el-table-column>
            <el-table-column prop="salt" label="角色" width="100" align="center">
                <template slot-scope="scope">
                    管理员
                </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" width="200" align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="200" sortable align="center" :formatter="formatDate"></el-table-column>
            <el-table-column prop="createTime" label="最后登录时间" width="200" sortable align="center" :formatter="formatDate"></el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button type="success" size="mini" @click="handleDetail(scope.row)">详情 <i class="el-icon-zoom-in"></i></el-button>
                    <el-button type="success" size="mini" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除 <i class="el-icon-remove-outline"></i></el-button>
                </template>
            </el-table-column>
        </el-table>
        
        <!-- 分页查询 -->
        <div style="padding: 10px 0; text-align: left;">
            <el-pagination
                 @size-change="handleSizeChange"
                 @current-change="handleCurrentChange"
                 :current-page="pageNum"
                 :page-sizes="[5, 10, 20, 50]"
                 :page-size="pageSize"
                 layout="total, sizes, prev, pager, next, -> , jumper"
                 :total="total">
            </el-pagination>
        </div>
        
        <!-- 数据新增界面 -->
        <el-dialog top="25vh" title="用户新增"
                   :visible.sync="dialogFormVisible"
                   append-to-body
                   :close-on-click-modal=true
                   width="30%"
        >
            <el-form ref="form" :model="form" label-width="120px" :rules="roles">
                <el-form-item label="用户名" prop="username">
                    <el-input prefix-icon="el-icon-user-solid" v-model="form.username" style="width: 90%"
                              placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input prefix-icon="el-icon-lock" v-model="form.password" style="width: 90%" show-password
                              placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirm">
                    <el-input prefix-icon="el-icon-lock" v-model="form.confirm" style="width: 90%" placeholder="请确认密码"
                              show-password></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickname">
                    <el-input prefix-icon="el-icon-user" v-model="form.nickname" style="width: 90%"
                              placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input prefix-icon="el-icon-message" v-model="form.email" style="width: 90%"
                              placeholder="请输入邮箱"><template slot="append">@qq.com</template></el-input>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input prefix-icon="el-icon-phone" v-model="form.mobile" style="width: 90%"
                              placeholder="请输入电话"></el-input>
                </el-form-item>
            </el-form>
            
            <template #footer>
          <span class="dialog-footer align-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveUser">确 定</el-button>
          </span>
            </template>
        </el-dialog>
        
        <!-- 数据详情界面 -->
        <el-dialog top="25vh" title="用户详情"
                   :visible.sync="dialogFormDetail"
                   append-to-body
                   :close-on-click-modal=false
                   width="30%"
        >
            <el-form ref="form" :model="form" label-width="120px">
                <el-form-item label="用户名" prop="username">
                    <el-input prefix-icon="el-icon-user-solid" v-model="form.username" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickname">
                    <el-input prefix-icon="el-icon-user" v-model="form.nickname" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input prefix-icon="el-icon-message" v-model="form.email" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input prefix-icon="el-icon-phone" v-model="form.mobile" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-input prefix-icon="el-icon-timer" v-model="form.createTime" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="启用状态">
                    <el-input prefix-icon="el-icon-star-off" v-model="form.status" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import {page, editUser, deleteUser, saveUser} from "@/api/system/user"
import dayjs from "dayjs";

export default {
    name: "User",
    data() {
        return {
            loading: false, // 列表等待转圈
            tableData: [],
            total: 10,
            pageNum: 1,
            pageSize: 10,
            headerBg: 'headerBg',
            dialogFormVisible: false, // 用户新增弹窗状态
            form: {}, // 用户新增数据集合
            roles: {
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                ],
                password: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                ],
                confirm: [
                    {required: true, message: '请确认密码', trigger: 'blur'},
                ],
                nickname: [
                    {required: true, message: '请输入用户昵称', trigger: 'blur'},
                ],
            },
            params: {}, // 查询条件
            dialogFormDetail: false, // 用户详情弹窗状态
            percent: 0,
            showProgress: false,
        }
    },
    created() {
        this.load()
    },
    methods: {
        handleSizeChange(pageSize) {
            console.log(pageSize)
            this.pageSize = pageSize;
            this.load()
        },
        handleCurrentChange(pageNum) {
            console.log(pageNum)
            this.pageNum = pageNum
            this.load()
        },
        load() {
            this.loading = true
            page(this.pageNum, this.pageSize, this.params).then(res => {
                this.loading = false
                this.tableData = res.data.records;
                this.total = res.data.total;
            }).catch(() => this.loading = false)
        },
        changSwitch(row) { // 开关

        },
        add() { // 新增用户按钮
            this.dialogFormVisible = true
            this.form = {}
        },
        saveUser() { // 添加用户
            if (this.form.password !== this.form.confirm) {
                this.$message({
                    type: "error",
                    message: '2次密码输入不一致！'
                })
                return
            }
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    const data = {
                        userId: this.form.userId,
                        username: this.form.username,
                        password: this.form.password.toLowerCase(),
                        nickname: this.form.nickname,
                        email: this.form.email + '@qq.com',
                        mobile: this.form.mobile,
                        status: this.form.status ? this.form.status : 1,
                        deptId: this.form.deptId,
                    }
                    if (data.userId) {
                        this.edit(data)
                    } else {
                        this.save(data)
                    }
                }
            })
        },
        handleDelete(user) { // 删除
            deleteUser(user.userId).then(res => {
                if (res.code === 200) {
                    this.$message({
                        type: "success",
                        message: "用户【" + user.username + "】删除成功"
                    })
                    this.load()
                } else {
                    this.$message({
                        type: "error",
                        message: res.msg
                    })
                }
            })
        },
        handleDetail(row) {
            this.form = JSON.parse(JSON.stringify(row))
            this.dialogFormDetail = true
        },
        handleEdit(row) {
            this.form = JSON.parse(JSON.stringify(row))
            this.form.password = '' // 密码重新输入
            if (this.form.email && this.form.email.indexOf('@qq.com') > -1) {
                this.form.email = this.form.email.substring(0, this.form.email.indexOf('@qq.com'))
            }
            this.dialogFormVisible = true
        },
        save(data) { // 新增数据
            saveUser(data).then(res => {
                if (res.code === 200) {
                    this.$message({
                        type: "success",
                        message: "用户新增成功"
                    })
                    this.load() // 刷洗表格数据
                    this.dialogFormVisible = false // 关闭弹窗
                } else {
                    this.$message({
                        type: "error",
                        message: res.msg
                    })
                }
            })
        },
        edit(data) { // 修改数据
            editUser(data).then(res => {
                if (res.code === 200) {
                    this.$message({
                        type: "success",
                        message: "用户【" + data.username + "】修改成功"
                    })
                    this.load() // 刷洗表格数据
                    this.dialogFormVisible = false // 关闭弹窗
                } else {
                    this.$message({
                        type: "error",
                        message: res.msg
                    })
                }
            })
        },
        handleAvatarSuccess(res) { // 文件上传
            this.form.avatar = res.data
            this.$message.success("上传成功")
            // this.update()
        },
        // -------------------------------------上传头像前的校验----------------------------------
        beforeAvatarUpload(file) {
            const isPNG = file.type === 'image/png'
            const isLt2M = file.size / 1024 / 1024 < 2
            if (!isPNG) {
                this.$message.error('上传头像图片只能是 PNG 格式!')
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return isPNG && isLt2M
        },
        
        // 时间格式化
        formatDate(row, column) {
            // 获取单元格数据
            let data = row[column.property]
            if(data == null) {
                return ''
            }
            return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
        },
    }
}
</script>

<style scoped>
.align-footer {
    text-align: center;
}

.avatar-uploader {
    width: 80px;
    height: 80px;
    border: 1px #b6b9c1 solid;
}

</style>
